package com.heima.wemedia.controller.v1;

import com.heima.wemedia.service.impl.DifyWorkflowService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;


@RestController
@RequestMapping("/api/news")
public class NewsController {

    private final DifyWorkflowService difyWorkflowService;

    public NewsController(DifyWorkflowService difyWorkflowService) {
        this.difyWorkflowService = difyWorkflowService;
    }

    @PostMapping("/generate")
    public ResponseEntity<Map<String, String>> generateNews(@RequestBody Map<String, Object> request) {
        try {
            // 安全地提取query参数
            String userQuery = "";
            Object inputsObj = request.get("inputs");

            if (inputsObj instanceof Map) {
                Map<String, Object> inputs = (Map<String, Object>) inputsObj;
                Object qObj = inputs.get("q");
                if (qObj instanceof String) {
                    userQuery = (String) qObj;
                }
            } else {
                // 兼容旧的请求格式
                Object queryObj = request.get("query");
                if (queryObj instanceof String) {
                    userQuery = (String) queryObj;
                }
            }

            if (userQuery == null || userQuery.trim().isEmpty()) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "Query cannot be empty.");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 调用服务，生成新闻稿
            String newsArticle = difyWorkflowService.generateNews(userQuery);

            // 返回成功结果
            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("article", newsArticle);
            return ResponseEntity.ok(successResponse);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "Failed to generate news article: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * SSE流式生成新闻稿
     */
    @GetMapping("/stream/generate")
    public SseEmitter streamGenerateNews(@RequestParam String query) {
        SseEmitter emitter = new SseEmitter(0L); // 设置超时时间为永不超时

        // 异步处理新闻生成
        CompletableFuture.runAsync(() -> {
            try {
                difyWorkflowService.streamGenerateNews(query, emitter);
            } catch (Exception e) {
                try {
                    emitter.send(SseEmitter.event().name("error").data("Generation failed: " + e.getMessage()));
                } catch (IOException ioException) {
                    // 忽略
                }
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }


}
